package com.nz2004.smsplatform.strategy.service.impl;


import com.nz2004.smsplatform.common.constants.CacheConstants;
import com.nz2004.smsplatform.common.index.StandardSubmit;
import com.nz2004.smsplatform.strategy.service.FilterChain;
import com.nz2004.smsplatform.strategy.service.StrategyManager;
import com.nz2004.smsplatform.strategy.service.api.CacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Map;


/**
 * @author ReJoice
 *  SingletonObjects  Map集合中,有我全部的对象,包括策略过滤器链对象
 */
@Service
@Slf4j
public class StrategyManagerImpl implements StrategyManager {


    @Autowired          //  泛型注入(4.x版本的Spring才有)
    private Map<String, FilterChain> strategyFilter;   // 6个责任链模块

    private final String FIELD = "filters";

    @Resource
    private CacheService cacheService;

    @Override
    public void execute(StandardSubmit submit) {
        // 获取到全部的策略过滤器链
        log.info("【策略过滤器链Manager】  strategyFilter = {}",strategyFilter);
        // 并且以一定的顺序去执行
        // 生成一个全局唯一的id    客户id + incr
        Long sequence = cacheService.incr(CacheConstants.CACHE_PREFIX_SMS_SEQUENCE + submit.getClientID(), 1L);
        submit.setSequenceId(submit.getClientID() + "" + sequence);
        // 从Redis中获取执行顺序
        String filters = cacheService.hGet(CacheConstants.CACHE_PREFIX_CLIENT + submit.getClientID(), FIELD);
        // 将顺序以","分割  filters
        if(!StringUtils.isEmpty(filters)){
            String[] filterArray = filters.split(",");
            // 遍历filters的数组
            for (String filter : filterArray) {   //black
                // 通过strategyFilter的Map集合,获取指定的FilterChain
                FilterChain filterChain = strategyFilter.get(filter);
                // 调用方法
                boolean b = filterChain.strategy(submit);
                // 判断,如果返回结果为false 直接调用,直接结束.
                if(!b){
                    break;
                }
            }
        }
    }


}
